﻿Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Public Class ImageHolder

    Public bitmap As Bitmap = Nothing
    Public bitmapData As BitmapData = Nothing
    Public bitmapBounds As Rectangle = Nothing

    Public ImageBytes() As Byte = Nothing
    Public stride As ULong = 0
    Public total_size As Integer = 0
    Public isLocked As Boolean = False

    Public Shared Widening Operator CType(ByVal val As Bitmap) As ImageHolder
        Return New ImageHolder(val)
    End Operator

    Public Shared Widening Operator CType(ByVal val As ImageHolder) As Bitmap
        Return val.bitmap
    End Operator

    Public Sub New(ByRef bm As Bitmap)
        changeImage(bm)
    End Sub

    Public Sub New()
    End Sub

    Public Sub changeImage(ByRef bm As Bitmap)
        If isLocked Then bitmap.UnlockBits(bitmapData)
        bitmap = bm
        bitmapBounds = New Rectangle(0, 0, bitmap.Width, bitmap.Height)
        bitmapData = bitmap.LockBits(bitmapBounds, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppPArgb) 'Format1bppIndexed Format32bppPArgb
        stride = bitmapData.Stride
        total_size = bitmapData.Stride * bitmapData.Height
        bitmap.UnlockBits(bitmapData)
        ReDim ImageBytes(total_size)
        isLocked = False
    End Sub

    Public Sub lockBitmap()
        If isLocked Then Return
        isLocked = True
        bitmapData = bitmap.LockBits(bitmapBounds, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppPArgb)
        Marshal.Copy(bitmapData.Scan0, ImageBytes, 0, total_size)
    End Sub

    Public Sub lockBitmap(ByVal accessMode As Imaging.ImageLockMode)
        If isLocked Then Return
        isLocked = True
        bitmapData = bitmap.LockBits(bitmapBounds, accessMode, Imaging.PixelFormat.Format32bppPArgb)
        Marshal.Copy(bitmapData.Scan0, ImageBytes, 0, total_size)
    End Sub

    Public Sub unlockBitmap()
        If Not isLocked Then Return
        Marshal.Copy(ImageBytes, 0, bitmapData.Scan0, total_size)
        bitmap.UnlockBits(bitmapData)
        isLocked = False
    End Sub

    Public Sub kill()
        If isLocked Then unlockBitmap()
    End Sub

End Class
